package com.zhongshengnetwork.rightbe.lang.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
//import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
//import android.support.annotation.NonNull;
//import android.support.annotation.Nullable;
//import android.support.v4.content.ContextCompat;
//import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.pj.core.http.HttpImage;
import com.pj.core.managers.LogManager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.bindings.DiscoveryItemBinding;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GlideRoundTransform;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.NavUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.banner.BannerView;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.expandabletextview.ExpandableTextView;
import com.zhongshengnetwork.rightbe.gsonmodel.BannerModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangTypeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.ThirdDataNameModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.BestLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.CardViewActivity;
import com.zhongshengnetwork.rightbe.lang.activity.CircleActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangDetailActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangSearchActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangSearchResultActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SelfImagePreviewActivity;
import com.zhongshengnetwork.rightbe.lang.activity.ThirdLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by luojingxing on 2019/3/30.
 */

public class DiscoverLangFragment extends BaseAnalyticsFragment {

    private List<String> mapList;

    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private List<LangInfoModel> list;
    private ListView listview;
    private MyAdapter adapter = null;
    private View rootView;//缓存Fragment view
    private int imgW = 0;
    private int imgH = 0;

    public MainActivity mainActivity;

    private List<String> nameList;
    private PublishSelectPicPopupWindow menuWindow;
    private LangInfoModel mLangInfoModel;

    public String userid = null;

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;
    private RelativeLayout search_top;
    private RelativeLayout discover_lang_layout;

    //轮播推荐
    private float density = 0.0f;
    private int screenWidth = 0;
    private List<View> viewList;
    private List<BannerModel> bannerList;
    BannerView bannerView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        calculateImageWidth();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.discover_lang_layout, container, false);
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
            pageindex = 0;
            if (list == null){
                list = new ArrayList<LangInfoModel>();
            }

            int width = ScreenUtils.getScreenWidth(getActivity());
            density = ScreenUtils.getScreenDensity(getActivity());
            screenWidth = width;
            if (viewList == null){
                viewList = new ArrayList<View>();
            }
            if (bannerList == null){
                bannerList = new ArrayList<>();
            }

            if (nameList == null){
                nameList = new ArrayList<String>();
                nameList.add("分享给微信好友");
                nameList.add("分享到微信朋友圈");
                nameList.add("取消");
            }
            listview=(ListView) rootView.findViewById(R.id.lang_listview);
            if (adapter == null){
                adapter=new MyAdapter();
            }
            listview.setFocusable(false);
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.e("TAG","position="+position);
                    if (list == null || list.size() == 0){
                        return;
                    }
                    int index = position - 1;
                    while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                        index+=1;
                    }
                    onClickDetail(index);
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });
            search_top = (RelativeLayout) rootView.findViewById(R.id.search_top);
            search_top.setClickable(true);
            search_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getActivity() == null){
                        return;
                    }
                    Intent intent = new Intent(getActivity(), CircleActivity.class);
                    startActivity(intent);
                }
            });
            Log.e("TAG","重新加载了发现页面了");

            discover_lang_layout = (RelativeLayout) rootView.findViewById(R.id.discover_lang_layout);
            discover_lang_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
            listview.setDividerHeight((int)(AppThemeUtils.DividerHeight*ScreenUtils.getScreenDensity(CustomApplication.mContext)));
            search_top.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            RelativeLayout search_shape_layout = (RelativeLayout) rootView.findViewById(R.id.search_shape_layout);
            search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());
            mapList = NavUtils.initNav();
            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    private void calculateImageWidth() {
        int width = ScreenUtils.getScreenWidth(getActivity());
        int margin = getResources().getDimensionPixelSize(R.dimen.paddingLR);
        imgW = width - margin * 2;
        imgH = Math.round(imgW / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO);
        density = ScreenUtils.getScreenDensity(getActivity());
        screenWidth = width;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBroadcast();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        broadcastManager.unregisterReceiver(mItemViewListClickReceiver);
    }

    private void registerBroadcast(){
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastDefine.WX_Share_Result);//建议把它写一个公共的变量，这里方便阅读就不写了。
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }
    BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){
            System.out.println("OK");
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Share_Result)){
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                map.put("id", mLangInfoModel.getLangid());
                String url = "miniapp/"+"langappid"+"/sharelanginfo.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        avi.hide();
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            mLangInfoModel.setSharecount(mLangInfoModel.getSharecount()+1);
                            int index = list.indexOf(mLangInfoModel);
                            list.set(index,mLangInfoModel);
                            update();
                        }else {
                            CustomApplication.showTip(commonModel, getActivity());
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        avi.hide();
                    }
                });
            }
        }
    };

    private void update(){
        if (getActivity() == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void getFirstData(boolean isFirst){
        if (getActivity() == null){
            return;
        }
        if (listview == null || list == null){
            return;
        }
        if (list.size() == 0){
            //listview.startRefresh();
            if (mRefreshLayout != null){
                pageindex = 0;
                mRefreshLayout.autoRefresh();
            }
        }else {
            if (isFirst == true){
                //listview.smoothScrollToPosition(0);
                listview.setSelection(0);
            }
        }
    }

    private void getData(){
        if (listview == null){
            return;
        }
        CustomApplication.customApplication.isGettingData = true;
        new Thread(){
            @Override
            public void run() {
                super.run();
                //首次从缓存里面获取数据
                if(pageindex == 0){
                    updateBanner();
                }
                if (list.size() == 0 && pageindex == 0){
                    String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.DiscoverData,"");
                    if (!CommonUtils.isEmpty(data)){
                        final List<LangInfoModel> l = GsonTools.getUserLangInfoModel(data);
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (l != null && l.size() > 0){
                                    list.addAll(l);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
                Log.e("TAG","重新加载了发现数据");
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put(APIKey.typeKey,"4");
                map.put("pageindex",pageindex+"");
                map.put("pagerecords",Records+"");
                HttpsUtils.miniAppDo(map, "miniapp/langappid/getlanglist.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<LangInfoModel> l = GsonTools.getUserLangInfoModel(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        if (pageindex == 0){
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.DiscoverData,data);
                                        }
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        isHasMore = false;
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (pageindex == 0){
                                        //listview.smoothScrollToPosition(0);
                                        listview.setSelection(0);
                                    }
                                    pageindex += 1;
                                    CustomApplication.customApplication.isGettingData = false;

                                }
                            });
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    CustomApplication.customApplication.isGettingData = false;
                                    CustomApplication.showTip(commonModel, getActivity());
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                }
                                CustomApplication.customApplication.isGettingData = false;
                            }
                        });
                    }
                });
            }
        }.start();

    }

    private class MyAdapter extends BaseAdapter {
        private int roundCorner = 0;

        public MyAdapter() {
            roundCorner = getContext().getResources().getDimensionPixelSize(R.dimen.image_round_corner);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size()+1;
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position-1);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0){
                return 0;
            }
            return 1;
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            View view = null;
            int type = getItemViewType(position);
            if (type == 0){
                if (convertView == null){
                    view = View.inflate(getActivity(), R.layout.banner_item_layout,null);
                }else {
                    view = convertView;
                }
                bannerView = (BannerView) view.findViewById(R.id.banner);
                RelativeLayout banner_item_layout = (RelativeLayout) view.findViewById(R.id.banner_item_layout);
                //设置主题下的颜色
                banner_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                bannerView.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                bannerView.startLoop(true);
                ViewGroup.LayoutParams params = bannerView.getLayoutParams();
                params.width = (int)(screenWidth - density*20);
                params.height = (int)((screenWidth - density*20)/3);
                bannerView.setLayoutParams(params);
                if (viewList != null && viewList.size() > 0){
                    bannerView.setViewList(viewList);
                }
                return view;
            }

            position -= 1;
            LangInfoModel model = list.get(position);

            /*
            //convertView的复用
            DiscoveryItemBinding binding = null;
            if (convertView != null) {
                binding = (DiscoveryItemBinding) convertView.getTag(R.layout.discovery_item_layout);
            }
            if (binding == null) {
                binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.discovery_item_layout, parent, false);
                binding.getRoot().setTag(R.layout.discovery_item_layout, binding);
            }
            position -= 1;
            LangInfoModel model = list.get(position);
            ImageView lang_user_header = binding.langUserHeader;
            ImageView privateIcon = binding.privateIcon;
            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                Glide.with(getActivity()).load(model.getPrivateIcon()).transform(new CircleTransform(getActivity())).dontAnimate().into(privateIcon);
            }else {
                privateIcon.setVisibility(View.GONE);
            }
            FrameLayout lang_user_header_layout = binding.langUserHeaderLayout;
            lang_user_header_layout.setTag(position);
            lang_user_header_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickUser((int)v.getTag());
                }
            });
            TextView lang_user_nickname = binding.langUserNickname;
            lang_user_nickname.setTag(position);
            lang_user_nickname.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickUser((int)v.getTag());
                }
            });
            TextView lang_time = binding.langTime;
            Button lang_care = binding.langCare;
            lang_care.setTag(position);
            lang_care.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickCare((int)v.getTag());
                }
            });
            ExpandableTextView lang_content = binding.langContent;
            Glide.with(getActivity()).load(model.getHeader()).transform(new CircleTransform(getActivity())).dontAnimate().into(lang_user_header);
            lang_user_nickname.setText(model.getNickname());

            //最新全部展示时间
            if (!CommonUtils.isEmpty(model.getSign())){
                lang_time.setText(model.getSign()+" · 阅读量: "+model.getExploreCount());
            }else {
                lang_time.setText("阅读量: "+model.getExploreCount());
            }


            if (model.iscare() == true){
                lang_care.setVisibility(View.INVISIBLE);
            }else {
                lang_care.setVisibility(View.VISIBLE);
            }
            lang_content.setText(model.getTitle(),position);

            //设置主题下的颜色
            RelativeLayout lang_item_layout = binding.langItemLayout;
            lang_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            lang_user_nickname.setTextColor(AppThemeUtils.getInstance().getUserNameColorOfWeiJu());
            lang_content.mTvContent.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            View lang_item_line = binding.langItemLine;
            lang_item_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            LinearLayout lang_op_layout = binding.langOpLayout;//(LinearLayout)view.findViewById(R.id.lang_op_layout);
            Button lang_op1 = binding.langOp1;//(Button) view.findViewById(R.id.lang_op1);
            lang_op1.setTag(position);
            lang_op1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickDelete((int)v.getTag());
                }
            });
            if (!CommonUtils.isEmpty(model.getLocation())){
                lang_op_layout.setVisibility(View.VISIBLE);
                lang_op1.setVisibility(View.VISIBLE);
                lang_op1.setText(model.getCity()+"  ·  "+model.getLocation());
            }else {
                lang_op_layout.setVisibility(View.GONE);
                lang_op1.setVisibility(View.GONE);
            }

            ImageView up_img_1 = binding.upImg1;
            ViewGroup up_img_layout = binding.upImgLayout;

            up_img_layout.setVisibility(View.GONE);

            if (model.getImglist() == null){

            }else if (model.getImglist().size() > 0){
                up_img_layout.setVisibility(View.VISIBLE);
                up_img_1.setVisibility(View.VISIBLE);
                up_img_layout.setVisibility(View.VISIBLE);
                up_img_layout.setTag(position+",1");
                up_img_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("TAG","点击了图片:"+v.getTag());
                        onClickImageView(v);
                    }
                });
                ViewGroup.LayoutParams params = up_img_1.getLayoutParams();
                params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                int height = Math.round(imgW / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO);
                params.height = height;
                up_img_1.setLayoutParams(params);
                up_img_1.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

                Glide.with(getActivity()).load(model.getImglist().get(0)).dontAnimate().placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).error(AppThemeUtils.getInstance().getDefaultImageBg()) .transform(new CenterCrop(),new GlideRoundTransform(getActivity(), Constant.LangCornerRadius)).into(up_img_1);

            }

            ImageView lang_share_img = binding.langShareImg;
            TextView lang_share_text = binding.langShareText;
            if (model.getSharecount() == 0){     lang_share_text.setText("分享"); }else {     lang_share_text.setText(CommonUtils.getDisplayCount(model.getSharecount())); }

            ImageView lang_collect_img = binding.langCollectImg;
            TextView lang_collect_text = binding.langCollectText;
            if (model.iscollect() == true){
                lang_collect_img.setImageResource(R.drawable.collection_sel);
                lang_collect_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.lightGreenColor));
            }else {
                lang_collect_img.setImageResource(R.drawable.collection);
                lang_collect_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
            }
            if (model.getCollectcount() == 0){     lang_collect_text.setText("收藏"); }else {     lang_collect_text.setText(CommonUtils.getDisplayCount(model.getCollectcount())); }

            ImageView lang_like_img = binding.langLikeImg;
            TextView lang_like_text = binding.langLikeText;
            if (model.islike() == true){
                lang_like_img.setImageResource(R.drawable.workgroup_img_like_sel);
                lang_like_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.lightGreenColor));
            }else {
                lang_like_img.setImageResource(R.drawable.workgroup_img_like);
                lang_like_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.defaultSmallFontColor));
            }
            if (model.getLikecount() == 0){
                if(model.getType() == 21 || model.getType() == 30){
                lang_like_text.setText("喜欢");
            }else if (model.getType() == 44){
                lang_like_text.setText("同感");
            }else {
                lang_like_text.setText("笔芯");
            } }else {     lang_like_text.setText(CommonUtils.getDisplayCount(model.getLikecount())); }

            ImageView lang_share_comment = binding.langShareComment;
            TextView lang_comment_text = binding.langCommentText;
            if (model.getCommentcount() == 0){     lang_comment_text.setText("评论"); }else {     lang_comment_text.setText(CommonUtils.getDisplayCount(model.getCommentcount())); }
            RelativeLayout lang_share = binding.langShare;
            lang_share.setTag(position);
            lang_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickShare((int)v.getTag(),v);
                }
            });

            RelativeLayout lang_collect = binding.langCollect;
            lang_collect.setTag(position);
            lang_collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickCollect((int)v.getTag());
                }
            });

            RelativeLayout lang_like = binding.langLike;
            lang_like.setTag(position);
            lang_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickLike((int)v.getTag());
                }
            });
            RelativeLayout lang_comment = binding.langComment;
            lang_comment.setTag(position);
            lang_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickDetail((int)v.getTag());
                }
            });

            return binding.getRoot();
            */

            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.banner_lang_item_layout,null);
            }
            view=convertView;

            ImageView lang_user_header = (ImageView) view.findViewById(R.id.lang_user_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                Glide.with(getActivity()).load(model.getPrivateIcon()).transform(new CircleTransform(getActivity())).dontAnimate().into(privateIcon);
            }else {
                privateIcon.setVisibility(View.GONE);
            }

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                Glide.with(getActivity()).load(model.getMemberIcon()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            FrameLayout lang_user_header_layout = (FrameLayout) view.findViewById(R.id.lang_user_header_layout);
            lang_user_header_layout.setTag(position);
            lang_user_header_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickUser((int)v.getTag());
                }
            });
            TextView lang_user_nickname = (TextView) view.findViewById(R.id.lang_user_nickname);
            lang_user_nickname.setTag(position);
            lang_user_nickname.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickUser((int)v.getTag());
                }
            });
            TextView lang_time = (TextView) view.findViewById(R.id.lang_time);
            Button lang_care = (Button) view.findViewById(R.id.lang_care);
            lang_care.setTag(position);
            lang_care.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickCare((int)v.getTag());
                }
            });
            ExpandableTextView lang_content = (ExpandableTextView)view.findViewById(R.id.lang_content);
            lang_content.setOnExpandStateChangeListener(new ExpandableTextView.OnExpandStateChangeListener() {
                @Override
                public void onExpandStateChanged(TextView textView, boolean isExpanded) {

                }

                @Override
                public void onClickContentText(int position) {
                    onClickDetail(position);
                }

                @Override
                public void onLongPressContentText(int position) {
                    if (getActivity() == null){
                        return;
                    }
                    if (list == null || list.size() == 0){
                        return;
                    }
                    if (position >= list.size()){
                        return;
                    }
                    LangInfoModel model = list.get(position);
                    CommonUtils.copy(getActivity(), model.getTitle(), model.isOriginal(), model.getLangid());
                }

                @Override
                public void onDoubleContentText(int position) {
                    onClickLike(position);
                }

            });
            Glide.with(getActivity()).load(model.getHeader()).transform(new CircleTransform(getActivity())).dontAnimate().into(lang_user_header);
            lang_user_nickname.setText(model.getNickname());


            if (CommonUtils.isEmpty(model.getTypename())){
                model.setTypename("微句");
            }

            if (!CommonUtils.isEmpty(model.getSign())){
                lang_time.setText(model.getSign()+" · "+model.getTypename());//+" · 阅读量: "+model.getExploreCount()
            }else {
                lang_time.setText(model.getTypename());//+" · "+"阅读量: "+model.getExploreCount()
            }

            if (model.iscare() == true){
                lang_care.setVisibility(View.INVISIBLE);
            }else {
                lang_care.setVisibility(View.VISIBLE);
            }
            lang_content.setText(model.getTitle(),position);

            //设置主题下的颜色
            RelativeLayout lang_item_layout = (RelativeLayout) view.findViewById(R.id.lang_item_layout);
            lang_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            lang_user_nickname.setTextColor(AppThemeUtils.getInstance().getUserNameColorOfWeiJu());
            lang_content.mTvContent.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            View lang_item_line = (View) view.findViewById(R.id.lang_item_line);
            lang_item_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            lang_time.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());

            LinearLayout lang_op_layout = (LinearLayout)view.findViewById(R.id.lang_op_layout);
            Button lang_op1 = (Button) view.findViewById(R.id.lang_op1);
            lang_op1.setTag(position);
            lang_op1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickDelete((int)v.getTag());
                }
            });

            if (!CommonUtils.isEmpty(model.getLocation())){
                lang_op_layout.setVisibility(View.VISIBLE);
                lang_op1.setVisibility(View.VISIBLE);
                lang_op1.setText(model.getCity()+"  ·  "+model.getLocation());
            }else {
                lang_op_layout.setVisibility(View.GONE);
                lang_op1.setVisibility(View.GONE);
            }


            FrameLayout up_img_layout = (FrameLayout) view.findViewById(R.id.up_img_layout);
            ImageView up_img_1 = (ImageView) view.findViewById(R.id.up_img_1);

            ViewGroup.LayoutParams params = up_img_1.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            int height = imgH;
            params.height = height;
            up_img_1.setLayoutParams(params);

            com.zhongshengnetwork.rightbe.common.ImageBanner.BannerView bannerView = (com.zhongshengnetwork.rightbe.common.ImageBanner.BannerView) view.findViewById(R.id.banner_view);
            params = bannerView.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = height;
            bannerView.setLayoutParams(params);

            TextView img_count = (TextView) view.findViewById(R.id.img_count);


            if (model.getImglist() == null){
                bannerView.setVisibility(View.GONE);
                up_img_layout.setVisibility(View.GONE);
                img_count.setVisibility(View.GONE);
            }else{
                if (model.getImglist().size() > 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                    bannerView.setVisibility(View.VISIBLE);
                    img_count.setVisibility(View.VISIBLE);
                    up_img_layout.setVisibility(View.GONE);
                    bannerView.setDataList(model.getImglist(), listview, position+1, img_count, getActivity(), imgW, imgH, model.getSmallImg());
                }else {
                    if (model.getImglist().size() > 1){
                        img_count.setVisibility(View.VISIBLE);
                        img_count.setText(model.getImglist().size()+"张");
                    }else {
                        img_count.setVisibility(View.GONE);
                    }
                    bannerView.setVisibility(View.GONE);
                    up_img_layout.setVisibility(View.VISIBLE);
                    up_img_layout.setClickable(true);
                    up_img_layout.setTag(position+",1");
                    up_img_layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("TAG","点击了图片:"+v.getTag());
                            onClickImageView(v);
                        }
                    });
                    Glide.with(getActivity()).load(model.getImglist().get(0)+CommonUtils.formatString(model.getSmallImg())).dontAnimate().placeholder(AppThemeUtils.getInstance().getDefaultBitmap()).error(AppThemeUtils.getInstance().getDefaultBitmap()) .transform(new CenterCrop(),new GlideRoundTransform(getActivity(), Constant.LangCornerRadius)).into(up_img_1);

                }

            }

            ImageView lang_share_img = (ImageView) view.findViewById(R.id.lang_share_img);
            TextView lang_share_text = (TextView) view.findViewById(R.id.lang_share_text);
            lang_share_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
            if (model.getSharecount() == 0){     lang_share_text.setText("分享"); }else {     lang_share_text.setText(CommonUtils.getDisplayCount(model.getSharecount())); }

            ImageView lang_collect_img = (ImageView) view.findViewById(R.id.lang_collect_img);
            TextView lang_collect_text = (TextView) view.findViewById(R.id.lang_collect_text);
            if (model.iscollect() == true){
                lang_collect_img.setImageResource(R.drawable.collection_sel);
                lang_collect_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.lightGreenColor));
            }else {
                lang_collect_img.setImageResource(R.drawable.collection);
                lang_collect_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
            }
            if (model.getCollectcount() == 0){     lang_collect_text.setText("收藏"); }else {     lang_collect_text.setText(CommonUtils.getDisplayCount(model.getCollectcount())); }

            ImageView lang_like_img = (ImageView) view.findViewById(R.id.lang_like_img);
            TextView lang_like_text = (TextView) view.findViewById(R.id.lang_like_text);
            if (model.islike() == true){
                lang_like_img.setImageResource(R.drawable.workgroup_img_like_sel);
                lang_like_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.lightGreenColor));
            }else {
                lang_like_img.setImageResource(R.drawable.workgroup_img_like);
                lang_like_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
            }
            if (model.getLikecount() == 0){     if(model.getType() == 21 || model.getType() == 30){
                lang_like_text.setText("喜欢");
            }else if (model.getType() == 44){
                lang_like_text.setText("同感");
            }else {
                lang_like_text.setText("笔芯");
            } }else {     lang_like_text.setText(CommonUtils.getDisplayCount(model.getLikecount())); }

            ImageView lang_share_comment = (ImageView) view.findViewById(R.id.lang_share_comment);
            TextView lang_comment_text = (TextView) view.findViewById(R.id.lang_comment_text);
            lang_comment_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
            if (model.getCommentcount() == 0){     lang_comment_text.setText("评论"); }else {     lang_comment_text.setText(CommonUtils.getDisplayCount(model.getCommentcount())); }
            RelativeLayout lang_share = (RelativeLayout) view.findViewById(R.id.lang_share);
            lang_share.setTag(position);
            lang_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickShare((int)v.getTag(),v);
                }
            });

            RelativeLayout lang_collect = (RelativeLayout) view.findViewById(R.id.lang_collect);
            lang_collect.setTag(position);
            lang_collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickCollect((int)v.getTag());
                }
            });

            RelativeLayout lang_like = (RelativeLayout) view.findViewById(R.id.lang_like);
            lang_like.setTag(position);
            lang_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickLike((int)v.getTag());
                }
            });
            RelativeLayout lang_comment = (RelativeLayout) view.findViewById(R.id.lang_comment);
            lang_comment.setTag(position);
            lang_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickDetail((int)v.getTag());
                }
            });

            return view;

        }
    }

    //点击图片处理
    private void onClickImageView(final View view){
        if (list == null || list.size() == 0){
            return;
        }

        if (getActivity() == null){
            return;
        }

        if (CustomApplication.isWatchingImg == true){
            return;
        }
        CustomApplication.isWatchingImg = true;

        String tag = view.getTag().toString();
        List<String> l = CommonUtils.stringToArrayList(tag);
        LangInfoModel model = list.get(Integer.valueOf(l.get(0)));
        String mSamllImg = model.getImgEnd();
        int position = Integer.valueOf(l.get(1))-1;
        Intent intent = new Intent(getActivity(), SelfImagePreviewActivity.class);
        intent.putExtra("position",position);
        intent.putExtra("isListImg",true);
        List<String> list = CommonUtils.stringToArrayList(model.getImg());
        intent.putExtra("imgs",list.get(0));
        //View代表方法传入的控件
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);
        int viewX = viewLocation[0]; // x 坐标
        int viewY = viewLocation[1]-(int) (20*ScreenUtils.getScreenDensity(CustomApplication.mContext)); // y 坐标，这里当顶部有状态栏时，要减去状态栏的高度
        intent.putExtra("viewX",viewX);
        intent.putExtra("viewY",viewY);
        intent.putExtra("imgW",imgW);
        intent.putExtra("imgH",imgH);
        getActivity().startActivity(intent);
        getActivity().overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.


    }

    //点击头像和昵称
    private void onClickUser(int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        if (position >= list.size()){
            return;
        }
        LangInfoModel model = list.get(position);
        //进入个人主页
        Intent intent = new Intent(getActivity(), UserLangActivity.class);
        intent.putExtra(APIKey.useridKey,model.getUserid());
        intent.putExtra(APIKey.typeKey,1);
        intent.putExtra(APIKey.titleKey,model.getNickname());
        startActivity(intent);
    }

    //点击关注
    private void onClickCare(final int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final LangInfoModel model = list.get(position);
        if (model.iscare() == true){
            return;
        }
        model.setIscare(true);
        list.set(position,model);
        adapter.notifyDataSetChanged();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("authorid", model.getUserid());
        String url = "miniapp/"+"langappid"+"/addcare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    //点击了详情
    private void onClickDetail(int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        if (position >= list.size()){
            return;
        }
        LangInfoModel model = list.get(position);
        Intent intent = new Intent(getActivity(), LangDetailActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", model);//序列化
        intent.putExtras(bundle);//发送数据
        startActivity(intent);
    }

    //点击了分享
    private void onClickShare(int position, View v){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        final LangInfoModel model = list.get(position);
        Intent intent = new Intent(getActivity(), LangDetailActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", model);//序列化
        bundle.putBoolean("share",true);
        intent.putExtras(bundle);//发送数据
        startActivity(intent);

    }

    //笔芯了收藏
    private void onClickCollect(final int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final LangInfoModel model = list.get(position);
        if (model.iscollect() == true){//修改二
            model.setIscollect(false);
            if (model.getCollectcount() > 0){
                model.setCollectcount(model.getCollectcount()-1);
            }
            list.set(position,model);
            adapter.notifyDataSetChanged();
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", model.getLangid());
            String url = "miniapp/"+"langappid"+"/cancleCollect.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    Log.e("TAG","笔芯结果："+data);
                }

                @Override
                public void onError(String msg) {
                }
            });
            return;
        }
        model.setIscollect(true);
        model.setCollectcount(model.getCollectcount()+1);
        list.set(position,model);
        adapter.notifyDataSetChanged();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("sourceid", model.getLangid());
        map.put(APIKey.typeKey,"1");
        String url = "miniapp/"+"langappid"+"/addcollection.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","收藏结果："+data);
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    //点击了笔芯
    private void onClickLike(final int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final LangInfoModel model = list.get(position);
        if (model.islike() == true){//修改之一
            model.setIslike(false);
            if (model.getLikecount() > 0){
                model.setLikecount(model.getLikecount()-1);
            }
            list.set(position,model);
            adapter.notifyDataSetChanged();
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", model.getLangid());
            String url = "miniapp/"+"langappid"+"/canclelike.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    Log.e("TAG","笔芯结果："+data);
                }

                @Override
                public void onError(String msg) {
                }
            });
            return;
        }
        model.setIslike(true);
        model.setLikecount(model.getLikecount()+1);
        list.set(position,model);
        adapter.notifyDataSetChanged();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("id", model.getLangid());
        map.put(APIKey.typeKey,"1");
        map.put("answerid","0");
        String url = "miniapp/"+"langappid"+"/langcl.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","笔芯结果："+data);
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button://分享给微信好友
                    shareToWX(1);
                    break;
                case R.id.second_button://分享到微信朋友圈
                    shareToWX(0);
                    break;
                case R.id.third_button:
                    break;
                default:
                    break;
            }

        }
    };

    //分享文字到微信
    private void shareToWX(int type){

        WXTextObject textObject = new WXTextObject();
        textObject.text = mLangInfoModel.getTitle();

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObject;
        msg.description = mLangInfoModel.getTitle();

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    /***************以下轮播相关****************/
    private void updateBanner(){
        //首次从缓存里面获取数据
        Log.e("TAG","首次从缓存里面获取数据Banner");
        if (bannerList == null){
            bannerList = new ArrayList<>();
        }
        if (bannerList.size() == 0){
            String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.FindBannerData,"");
            if (!CommonUtils.isEmpty(data)){
                List<BannerModel> l = GsonTools.getBannerModel(data);
                if (l != null && l.size() > 0){
                    bannerList.addAll(l);
                    String bgUrl = GsonTools.getFindBannerBgUrl(data);
                    if (!CommonUtils.isEmpty(bgUrl)){
                        BannerModel model = new BannerModel();
                        Byte type = -10;
                        model.setType(type);
                        model.setSourceid("");
                        model.setContent("");
                        model.setImg(bgUrl);
                        model.setFontcolor("000000");
                        model.setFontname("");
                        model.setFontsize(18.0f);
                        bannerList.add(model);
                    }
                }else {
                    BannerModel model = new BannerModel();
                    Byte type = 0;
                    model.setType(type);
                    model.setSourceid("");
                    model.setContent("对自己好点，因为一辈子不长；对身边的人好点，因为下辈子不一定能够遇见！");
                    model.setImg("http://image.daydayrise.net/wordbg181012.png");
                    model.setFontcolor("000000");
                    model.setFontname("");
                    model.setFontsize(18.0f);
                    bannerList.add(model);
                }
                upateBannerUI();
            }else {
                BannerModel model = new BannerModel();
                Byte type = 0;
                model.setType(type);
                model.setSourceid("");
                model.setContent("对自己好点，因为一辈子不长；对身边的人好点，因为下辈子不一定能够遇见！");
                model.setImg("http://image.daydayrise.net/wordbg181012.png");
                model.setFontcolor("000000");
                model.setFontname("");
                model.setFontsize(18.0f);
                bannerList.add(model);
                upateBannerUI();
            }
        }

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        String url = "miniapp/"+"langappid"+"/find/banner.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","轮播数据："+data);
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    List<BannerModel> l = GsonTools.getBannerModel(data);
                    if (l != null && l.size() > 0){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.FindBannerData,data);
                        bannerList.clear();
                        bannerList.addAll(l);
                        String bgUrl = GsonTools.getFindBannerBgUrl(data);
                        if (!CommonUtils.isEmpty(bgUrl)){
                            BannerModel model = new BannerModel();
                            Byte type = -10;
                            model.setType(type);
                            model.setSourceid("");
                            model.setContent("");
                            model.setImg(bgUrl);
                            model.setFontcolor("000000");
                            model.setFontname("");
                            model.setFontsize(18.0f);
                            bannerList.add(model);
                        }
                        upateBannerUI();
                    }
                }
            }

            @Override
            public void onError(String msg) {
                Log.e("TAG","轮播数据失败："+msg);
            }
        });

    }

    private void upateBannerUI(){
        if (getActivity() == null){
            return;
        }
        if (viewList == null){
            viewList = new ArrayList<View>();
        }
        if (bannerView == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                viewList.clear();
                for (int i = 0; i < bannerList.size(); i++) {
                    if (getActivity() == null){
                        continue;
                    }
                    BannerModel model = bannerList.get(i);
                    RelativeLayout layout = new RelativeLayout(getActivity());
                    layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

                    ImageView image = new ImageView(getActivity());
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    //设置显示格式
                    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    image.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                    RequestOptions options = new RequestOptions().error(AppThemeUtils.getInstance().getDefaultImageBg()).bitmapTransform(new RoundedCorners(25));//图片圆角
                    if (CommonUtils.isEmpty(model.getImg())){
                        Glide.with(getActivity()).load("http://image.daydayrise.net/wordbg181012.png").apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(image);
                    }else {
                        Glide.with(getActivity()).load(model.getImg()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(image);
                    }
                    layout.addView(image);

                    if (model.getType() == 0 || model.getType() == 2 || model.getType() == 4){
                        final TextView textView = new TextView(getActivity());
                        ViewGroup.LayoutParams l = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        textView.setLayoutParams(l);
                        textView.setTag(i);
                        if(model.getFontsize() == null){
                            textView.setTextSize(16);
                        }else {
                            textView.setTextSize(model.getFontsize()-2);
                        }
                        textView.setText(CommonUtils.formatString(model.getContent()));
                        textView.setGravity(Gravity.CENTER);
                        if (CommonUtils.isEmpty(model.getFontcolor())){
                            textView.setTextColor(Color.parseColor("#000000"));
                        }else {
                            textView.setTextColor(Color.parseColor("#"+model.getFontcolor()));
                        }
                        textView.setBackgroundColor(Color.parseColor("#00000000"));
                        textView.setPadding((int)(22),(int)(45),(int)(22),(int)(45));
                        textView.setLineSpacing(10,1);
                        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));//加粗斜体
                        textView.getPaint().setFakeBoldText(true);//加粗
                        textView.setMaxLines(2);
                        textView.setEllipsize(TextUtils.TruncateAt.END);
                        layout.addView(textView);
                    }

                    layout.setTag(i);
                    layout.setClickable(true);
                    layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("TAG","点击："+v.getTag());
                            onClickBanner((int)v.getTag());
                        }
                    });
                    viewList.add(layout);
                }
                bannerView.setViewList(viewList);
            }
        });
    }

    //处理点击事件
    private void onClickBanner(final int index){
        if (bannerList != null && bannerList.size() > index){
            BannerModel model = bannerList.get(index);
            if (model.getType() == 0 || model.getType() == 4) {
                if (getActivity() == null){
                    return;
                }
                //微句
                dealWithLang(model.getSourceid());
            }else if (model.getType() == 1){
                if (getActivity() == null){
                    return;
                }
                //链接
                if (!CommonUtils.isEmpty(model.getContent())){
                    Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, model.getContent());
                    startActivity(webIntent);
                }
            }else if (model.getType() == 3){
                //微句类型
                if (!CommonUtils.isEmpty(model.getContent())){
                    dealWithLangType(model.getContent());
                }
            }else if (model.getType() == -100){
                if (getActivity() == null){
                    return;
                }
                //专题内容
                Intent intent = new Intent(getActivity(), ThirdLangActivity.class);
                intent.putExtra(APIKey.typeKey,model.getTypeid());
                intent.putExtra(APIKey.nameKey,model.getName());
                startActivity(intent);
            }else if (model.getType() == -10){
                //每日推荐
                Intent intent = new Intent(getActivity(), BestLangActivity.class);
                intent.putExtra("title","金句推荐");
                startActivity(intent);
            }
        }
    }

    //微句类型
    private void dealWithLangType(String title){
        if (getActivity() == null){
            return;
        }
        int type = 0;
        String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LangTypeName,"");
        if (!CommonUtils.isEmpty(data)){
            List<LangTypeModel>l = GsonTools.getLangTypeModel(data);
            if (l != null && l.size() > 0){
                for (int i = 0; i < l.size(); i++){
                    LangTypeModel m = l.get(i);
                    if (m.getName().equals(title)){
                        type = m.getId();
                        break;
                    }
                }
            }
        }
        Intent intent = new Intent(getActivity(), LangSearchResultActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("title",title);
        startActivity(intent);
    }

    //微句
    private void dealWithLang(String langid){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);
                    if (langInfoModel.getStatus() == 1){
                        Intent intent = new Intent(getActivity(), LangDetailActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }


    //以下是导航相关
    private void onClickDelete(final int position){
        if (getActivity() == null){
            return;
        }
        if (list == null || list.size() == 0){
            return;
        }

        if (mapList == null || mapList.size() == 0){
            return;
        }
        final LangInfoModel model = list.get(position);
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : mapList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = mapList.get(which-1);
                        if (title.equals("高德地图")){
                            NavUtils.gaodeNav(getActivity(), model.getCity(),model.getLocation(),model.getLatitude()+"",model.getLongtitude()+"");
                        }else if (title.equals("百度地图")){
                            NavUtils.baiduNav(getActivity(), model.getCity(),model.getLocation(),model.getLatitude()+"",model.getLongtitude()+"");
                        }else if (title.equals("腾讯地图")){
                            NavUtils.openTencentMap(getActivity(), 0, 0, null, model.getLatitude(), model.getLongtitude(), model.getLocation());
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

}

